package com.xyzwps.lib.json.element;

public final class CompactStringifierVisitor implements JsonElementVisitor<String> {

    private CompactStringifierVisitor() {
    }

    public static final CompactStringifierVisitor INSTANCE = new CompactStringifierVisitor();

    @Override
    public String visit(JsonArray ja) {
        var sb = new StringBuilder().append('[');
        if (!ja.isEmpty()) {
            sb.append(ja.getFirst().toString());
        }
        for (int i = 1; i < ja.size(); i++) {
            sb.append(',').append(ja.get(i).toString());
        }
        return sb.append(']').toString();
    }

    @Override
    public String visit(JsonBoolean jb) {
        return jb.stringValue;
    }

    @Override
    public String visit(JsonDecimal jd) {
        return jd.value().toString();
    }

    @Override
    public String visit(JsonInteger ji) {
        return ji.value().toString();
    }

    @Override
    public String visit(JsonNull jn) {
        return "null";
    }

    @Override
    public String visit(JsonObject jo) {
        var sb = new StringBuilder().append('{');
        var env = new Env();
        jo.forEach((key, value) -> {
            if (env.first) env.first = false;
            else sb.append(',');

            sb.append('"').append(JsonString.unescape(key)).append('"').append(':').append(value.toString());
        });

        return sb.append('}').toString();
    }

    private static class Env {
        boolean first = true;
    }

    @Override
    public String visit(JsonString js) {
        return '"' + js.toUnescapedString() + '"';
    }

}
